package com.reebake.ideal.storage.vo;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Base64;


@Slf4j
public class Base64DecodedMultipartFile implements MultipartFile {

    private final byte[] imgContent;
    private final String header;
    private final String filename;
    private final String contentType;

    public Base64DecodedMultipartFile(byte[] imgContent, String rawHeader) {
        this.imgContent = imgContent;
        this.header = rawHeader.split(";")[0];
        String[] headers = this.header.split(":");
        this.contentType = headers[1];
        this.filename = RandomUtil.randomString(16) + "." + this.contentType.split("/")[1];
    }

    @Override
    public String getName() {
        return this.filename;
    }

    @Override
    public String getOriginalFilename() {
        return this.filename;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return imgContent == null || imgContent.length == 0;
    }

    @Override
    public long getSize() {
        return imgContent.length;
    }

    @Override
    public byte[] getBytes() {
        return imgContent;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(imgContent);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(dest);
            out.write(imgContent);
        } catch (Exception e) {
            throw e;
        }finally {
            IoUtil.close(out);
        }

    }

    public static MultipartFile base64ToMultipart(String base64) {
            String[] baseStrs = base64.split(",");

            byte[] b;
            b = Base64.getDecoder().decode(baseStrs[1]);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64DecodedMultipartFile(b, baseStrs[0]);
    }
}
